import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:toast/toast.dart';

import '../../http/api.dart';

class WebsiteAddPage extends StatefulWidget {
  const WebsiteAddPage({super.key});

  @override
  State<WebsiteAddPage> createState() => _WebsiteAddPageState();
}

class _WebsiteAddPageState extends State<WebsiteAddPage> {
  // 私有变量，网页名
  String? _name;
  // 私有变量 网页链接
  String? _link;
  // FormState的 id key 声明在此
  final _formkey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("收藏网址"),
      ),
      body: Form(
        key: _formkey,
        child: ListView(
          padding: EdgeInsets.fromLTRB(22.0, 18.0, 22.0, 0.0),
          children: [
            // edittext 文本输入框
            TextFormField(
              autofocus: true,
              // 带样式的输入框
              decoration: InputDecoration(
                labelText: '名称'
              ),
              // 检测输入类型正确性
              validator: (String? value){
                if(value!.trim().isEmpty) {
                  return '请输入收藏网址名';
                }
                _name = value;
              },
            ),
            TextFormField(
              initialValue: "http://",
              decoration: InputDecoration(
                labelText: "地址",
              ),
              keyboardType: TextInputType.url,
              // 输入为空则返回提示
              validator: (String? value) {
                if(value!.trim().isEmpty) {
                  return '请输入收藏网址';
                }
                _link = value;
              },
            ),
            Container(
              height: 45.0,
              margin: EdgeInsets.only(top: 18.0, left: 8.0, right: 8.0),
              child: ElevatedButton(
                child: Text(
                  '收藏',
                  style: TextStyle(fontSize: 18.0, color: Colors.white),
                ),
                style: ButtonStyle(backgroundColor: MaterialStateProperty.all(Colors.blue)),
                onPressed: ()=>_doAdd(context),
              ),
            )
          ],
        ),
      ),
    );
  }

  void _doAdd(context) async {
    if(_formkey.currentState!.validate()) {
      // 无法被隐藏的转圈对话框
      showDialog(context: context, barrierDismissible: false, builder: (_) {
        return Center(child: CircularProgressIndicator(),);
      });
      var result = await Api.collectWebsite(_name!, _link!);
      // 后退弹栈，和back一个效果，隐藏上面的转圈对话框
      Navigator.pop(context);
      if(result['errorCode'] != 0) {
        Toast.show(result['errorMsg'], gravity: Toast.center);
      }else {
        Navigator.pop(context, result['data']);
      }
    }
  }
}
